package com.ww.exercise.coroutine.hard.q18.opt

import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

// 打印结果
// IO任务最多2个同时执行
// 计算任务最多4个同时执行
// =========================================
//IO任务0在DefaultDispatcher-worker-1执行====
//IO任务1在DefaultDispatcher-worker-3执行====
//计算任务0在DefaultDispatcher-worker-2执行****
//计算任务1在DefaultDispatcher-worker-4执行****
//计算任务2在DefaultDispatcher-worker-5执行****
//计算任务3在DefaultDispatcher-worker-6执行****
//IO任务2在DefaultDispatcher-worker-1执行====
//计算任务5在DefaultDispatcher-worker-2执行****
//IO任务4在DefaultDispatcher-worker-1执行====
//计算任务4在DefaultDispatcher-worker-4执行****
//计算任务7在DefaultDispatcher-worker-5执行****
//计算任务6在DefaultDispatcher-worker-6执行****
//计算任务9在DefaultDispatcher-worker-4执行****
//计算任务8在DefaultDispatcher-worker-2执行****
//IO任务5在DefaultDispatcher-worker-1执行====
//IO任务3在DefaultDispatcher-worker-3执行====
//IO任务6在DefaultDispatcher-worker-3执行====
//IO任务7在DefaultDispatcher-worker-1执行====
//IO任务8在DefaultDispatcher-worker-3执行====
//IO任务9在DefaultDispatcher-worker-1执行====
//完成所有任务，耗时1022ms
//命名调度器: MyLimitedDispatcher
fun main() = runBlocking {
    // 示例1：限制IO调度器的并行度
    val limitedIODispatcher = Dispatchers.IO.limitedParallelism(2)
    // 示例2：限制默认调度器的并行度
    val limitedDefaultDispatcher = Dispatchers.Default.limitedParallelism(4)

    val time = measureTimeMillis {
        coroutineScope {
            repeat(10) {
                launch(limitedIODispatcher) {
                    println("IO任务${it}在${Thread.currentThread().name}执行====")
                    delay(1000)
                }
            }

            repeat(10) {
                launch(limitedDefaultDispatcher) {
                    println("计算任务${it}在${Thread.currentThread().name}执行****")
                    delay(500)
                }
            }
        }
    }
    println("完成所有任务，耗时${time}ms")

    // 示例3：命名调度器
    val namedDispatcher = Dispatchers.Default.limitedParallelism(2, "MyLimitedDispatcher")
    println("命名调度器: ${namedDispatcher}")
}